package com.youdianstar.app.ui

import android.Manifest
import android.content.pm.PackageManager
import android.location.Location
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MapStyleOptions
import com.google.android.gms.tasks.Task
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.BR
import com.youdianstar.app.R

import com.youdianstar.app.adapter.PlacesListAdapter
import com.youdianstar.app.databinding.ActivityMapPlaceBinding
import com.youdianstar.app.entity.PlacesEntity
import com.youdianstar.app.support.imp.IPlacesSelectListener
import com.youdianstar.app.util.DataAppManager
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: PlaceSearchActivity
 * Author: 82149 Create: 2023/7/14 11:42
 * Changes (from 2023/7/14)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class PlaceSearchActivity : BaseActivity<ActivityMapPlaceBinding,BranchViewModel>() {
    override fun layoutId(): Int = R.layout.activity_map_place

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): BranchViewModel {
        val model: BranchViewModel by viewModel()
        return model
    }

    private var mapFragment: SupportMapFragment? = null
    private var mPlaceMap: GoogleMap? = null
    private val zoomLevel = 16.0f
    private var currentLevel = 14.0F
    private var isMapReady = false
    private var isLocationReady = false

    private var placesData = mutableListOf<PlacesEntity>()
    private var mListAdapter : PlacesListAdapter?=null

    override fun initViewLayout() {
        super.initViewLayout()
        android.util.Log.d("PlaceSearchActivity", "初始化视图布局")
        mBinding.headBar.initTitle(this, title = "", showInner = false)
        mBinding.headBar.setRightText(getString(R.string.home_confirm),R.color.white) {
            //保存选择
        }
        mBinding.headBar.setRightEnable(R.color.color_71BFFF,false)

        android.util.Log.d("PlaceSearchActivity", "查找地图Fragment")
        mapFragment = supportFragmentManager.findFragmentById(R.id.map_place) as SupportMapFragment?
        if (mapFragment == null) {
            android.util.Log.e("PlaceSearchActivity", "地图Fragment未找到!")
        } else {
            android.util.Log.d("PlaceSearchActivity", "地图Fragment找到，开始异步加载")
        }
        mapFragment?.getMapAsync(object : OnMapReadyCallback {
            override fun onMapReady(googleMap: GoogleMap) {
                android.util.Log.d("PlaceSearchActivity", "地图准备就绪")
                mPlaceMap = googleMap
                mPlaceMap?.setPadding(0,0,0,16)
                
                //初始化地图样式
                try {
                    googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this@PlaceSearchActivity, R.raw.map_style))
                    android.util.Log.d("PlaceSearchActivity", "地图样式设置成功")
                } catch (e: Exception) {
                    android.util.Log.e("PlaceSearchActivity", "地图样式设置失败: ${e.message}")
                }

                //设置地图 监听事件
                if (isLocationReady) {
                    setMapReady()
                }
                //更新地图
                DataAppManager.instance.getLocalLatLng().let {
                    android.util.Log.d("PlaceSearchActivity", "更新地图相机位置: $it")
                    updateMapCamera(it)
                }
            }
        })
        initLocationPermission()
    }

    override fun initData() {
        super.initData()
        mBinding.rcyPlaces.layoutManager = LinearLayoutManager(this)
        mListAdapter = PlacesListAdapter(this, mutableListOf(), object :IPlacesSelectListener{
            override fun onPlacesClick(position: Int, item: PlacesEntity) {

            }
        })
        mBinding.rcyPlaces.adapter = mListAdapter
    }

    override fun initClickEvent() {
        mBinding.mapLocation.setThrottleListener {
            //更新地图定位
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                initLocationPermission()
            }else{
                getMapUserLocation()
            }
        }
    }


    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        super.onPermissionsGranted(requestCode, perms)
        LogUtil.i("---Granted-Perms:$perms")
        setLocationUpdateListener()
    }

    private fun initLocationPermission() {
        requestPermission(getString(R.string.Location_Permission_Tip), Manifest.permission.ACCESS_FINE_LOCATION,
            granted = {
                setLocationUpdateListener()
            })
    }

    private fun getMapUserLocation() {
        android.util.Log.d("PlaceSearchActivity", "📍 开始获取用户位置")
        try {
            val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
            val locationTask: Task<Location> = fusedLocationClient.lastLocation
            locationTask.addOnCompleteListener { task: Task<Location?> ->
                if (task.isSuccessful && null != task.result) {
                    val latL = LatLng(task.result!!.latitude, task.result!!.longitude)
                    android.util.Log.d("PlaceSearchActivity", "✅ 成功获取设备位置: $latL")
                    DataAppManager.instance.saveLocalLatLng(latL)
                    updateMapCamera(latL)
                    //获取 定位点反编译列表
                } else {
                    android.util.Log.w("PlaceSearchActivity", "⚠️ 获取设备位置失败，使用默认位置")
                    val defaultLocation = DataAppManager.instance.getDefaultLatLng()
                    android.util.Log.d("PlaceSearchActivity", "📍 使用默认位置（胡志明市）: $defaultLocation")
                    updateMapCamera(defaultLocation)
                }
            }
            locationTask.addOnFailureListener {
                android.util.Log.e("PlaceSearchActivity", "❌ 位置获取失败: ${it.message}")
                val defaultLocation = DataAppManager.instance.getDefaultLatLng()
                android.util.Log.d("PlaceSearchActivity", "📍 使用默认位置（胡志明市）: $defaultLocation")
                updateMapCamera(defaultLocation)
                //获取 定位点反编译列表
            }
        } catch (e: SecurityException) {
            android.util.Log.e("PlaceSearchActivity", "❌ 位置权限异常: ${e.message}")
            val defaultLocation = DataAppManager.instance.getDefaultLatLng()
            android.util.Log.d("PlaceSearchActivity", "📍 使用默认位置（胡志明市）: $defaultLocation")
            updateMapCamera(defaultLocation)
        }
    }

    /**原生定位获取方式*/
    private fun setLocationUpdateListener() {
        android.util.Log.d("PlaceSearchActivity", "🔐 检查位置权限状态")
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            android.util.Log.w("PlaceSearchActivity", "⚠️ 位置权限未授予，使用默认位置")
            val defaultLocation = DataAppManager.instance.getDefaultLatLng()
            android.util.Log.d("PlaceSearchActivity", "📍 使用默认位置（胡志明市）: $defaultLocation")
            updateMapCamera(defaultLocation)
            return
        }
        android.util.Log.d("PlaceSearchActivity", "✅ 位置权限已授予，开始获取设备位置")
        isLocationReady = true
        if (!isMapReady) {
            setMapReady()
        }
        getMapUserLocation()
    }

    //设置地图样式+事件监听
    private fun setMapReady() {
        mPlaceMap?.let { map ->
            LogUtil.e("----setMapReady")
            try {
                map.isMyLocationEnabled = false
                map.uiSettings.isMyLocationButtonEnabled = false
                map.uiSettings.isCompassEnabled = false
                map.uiSettings.isZoomControlsEnabled = false
                map.uiSettings.isMapToolbarEnabled = false
            } catch (e: SecurityException) {
                e.printStackTrace()
            }
            map.setOnCameraIdleListener {
                //地图中心点移动
            }
            map.setOnMapClickListener { latLng ->
                //地图点击
            }
            isMapReady = true
        }
    }

    /**刷新布局中心点*/
    private fun updateMapCamera(sydney: LatLng) {
        mPlaceMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, zoomLevel))
    }
}